package com.zytech.zspider.task;

import com.google.common.collect.Maps;
import com.zytech.modules.lang.Requires;
import com.zytech.zspider.core.TaskDefinition;

import java.util.Collections;
import java.util.Map;

/**
 * @author siuming
 */
public final class TaskContext {

    public static final String TASK = "_$task";
    public static final String TASK_RESULT = "_$result";
    public static final String FATHER_TASK = "_$father";
    public static final String FATHER_TASK_RESULT = "_$father_result";

    /**
     * empty context.
     */
    public static final TaskContext EMPTY = null;

    private final Map<String, Object> delegate = Maps.newHashMap();

    TaskContext() {
    }

    /**
     * @param name
     * @return
     */
    public Object getBinding(String name) {
        Requires.hasText(name, "name must not be empty or null.");
        return delegate.get(name);
    }

    /**
     * @return
     */
    public Map<String, Object> getAllBindings() {
        return Collections.unmodifiableMap(delegate);
    }

    /**
     * @param name
     * @param val
     */
    public void putBinding(String name, Object val) {
        Requires.hasText(name, "name must not be empty or null.");
        delegate.put(name, val);
    }

    /**
     * @param bindings
     */
    public void putAllBindings(Map<String, Object> bindings) {
        Requires.notNull(bindings, "bindings must not be null.");
        delegate.putAll(bindings);
    }

    /**
     * @return
     */
    public TaskContext copy() {
        TaskContext context = new TaskContext();
        context.putAllBindings(getAllBindings());
        return context;
    }


    /**
     * @param taskDefinition
     * @return
     */
    public static TaskContext of(TaskDefinition taskDefinition) {
        Requires.notNull(taskDefinition, "taskDefinition must not be null.");
        TaskContext context = new TaskContext();
        context.putBinding(TASK, taskDefinition);
        return context;
    }
}
